#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AIOT智能学习桌项目 - 日志系统
"""

import logging
import sys
from datetime import datetime
from pathlib import Path
from config import DATA_CONFIG, SYSTEM_CONFIG

class SmartDeskLogger:
    """智能学习桌日志管理器"""
    
    def __init__(self, name="SmartDesk", log_file=None):
        self.logger = logging.getLogger(name)
        self.logger.setLevel(getattr(logging, SYSTEM_CONFIG['log_level']))
        
        # 避免重复添加处理器
        if not self.logger.handlers:
            self._setup_handlers(log_file)
    
    def _setup_handlers(self, log_file):
        """设置日志处理器"""
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        )
        
        # 控制台处理器
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.setFormatter(formatter)
        self.logger.addHandler(console_handler)
        
        # 文件处理器
        if log_file is None:
            log_file = DATA_CONFIG['logs_dir'] / f"smartdesk_{datetime.now().strftime('%Y%m%d')}.log"
        
        file_handler = logging.FileHandler(log_file, encoding='utf-8')
        file_handler.setFormatter(formatter)
        self.logger.addHandler(file_handler)
    
    def debug(self, message):
        """调试信息"""
        self.logger.debug(message)
    
    def info(self, message):
        """一般信息"""
        self.logger.info(message)
    
    def warning(self, message):
        """警告信息"""
        self.logger.warning(message)
    
    def error(self, message):
        """错误信息"""
        self.logger.error(message)
    
    def critical(self, message):
        """严重错误"""
        self.logger.critical(message)

# 全局日志实例
logger = SmartDeskLogger()

def log_function_call(func):
    """函数调用日志装饰器"""
    def wrapper(*args, **kwargs):
        logger.debug(f"调用函数: {func.__name__}")
        try:
            result = func(*args, **kwargs)
            logger.debug(f"函数 {func.__name__} 执行成功")
            return result
        except Exception as e:
            logger.error(f"函数 {func.__name__} 执行失败: {e}")
            raise
    return wrapper

def log_error(error_type, error_message, context=None):
    """统一错误日志记录"""
    log_msg = f"[{error_type}] {error_message}"
    if context:
        log_msg += f" | 上下文: {context}"
    logger.error(log_msg)

def log_performance(operation, duration):
    """性能日志记录"""
    logger.info(f"性能统计 - {operation}: {duration:.3f}秒")

if __name__ == "__main__":
    # 测试日志系统
    logger.info("日志系统测试")
    logger.debug("这是调试信息")
    logger.warning("这是警告信息")
    logger.error("这是错误信息")